package com.unohacha.qqj.fzdr.main;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.bean.citybean.ProvinceBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeAppFzSchoolBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeSendYellowPageS;
import com.unohacha.qqj.fzdr.imp.MyApplication;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.util.FastUtils;
import com.unohacha.qqj.fzdr.util.GetJsonDataUtil;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.view.citypickview.CityPickerPopWindow2;
import com.unohacha.qqj.mylibrary.base.BaseActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 本地黄页发布
 */
public class LocationYellowSendActivity extends BaseActivity implements CityPickerPopWindow2.CityPickListener {

    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.home1_title)
    LinearLayout home1Title;
    @BindView(R.id.company_type_tv)
    TextView companyTypeTv;
    @BindView(R.id.show_area_tv)
    TextView showAreaTv;
    @BindView(R.id.detail_et)
    EditText detailEt;
    @BindView(R.id.send_tv)
    TextView send_tv;
    @BindView(R.id.company_name_et)
    EditText companyNameEt;
    @BindView(R.id.company_phone)
    EditText companyPhone;
    @BindView(R.id.root_layout)
    LinearLayout root_layout;
    @BindView(R.id.show_area_rl)
    RelativeLayout show_area_rl;
    @BindView(R.id.company_type_rl)
    RelativeLayout company_type_rl;

    private static final int MY_SEND_PAGE = 10007;//发布本地黄页的
    private List<ProvinceBean> options1Items = new ArrayList<>();
    private List<ProvinceBean.TwoRegBean> options2Items = new ArrayList<>();
    private List<ProvinceBean.TwoRegBean.ThreeRegBean> options3Items = new ArrayList<>();
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private Thread thread;
    private boolean isLoaded = false;
    private String province, city, district;
    private String  provinceId = "1";// 省id
    private String cityId = "2";//市 id
    private String distristId = "3";//区id
    private List<HomeAppFzSchoolBean.DataBean> mCateList = new ArrayList<>();
    private int companyId;//企业Id
    private String companyType;//企业名称
    private int app_cate_id;//分类Id
    
    @Override
    protected int getLayoutId() {
        return R.layout.activity_location_yellow_send;
    }

    @Override
    protected void initView() {
        super.initView();
        if (null != getIntent()){
            app_cate_id = getIntent().getIntExtra("app_cate_id",0);
        }
        commonTitle.setText(getResources().getString(R.string.yellow_page_send));
        commonRightImage.setVisibility(View.GONE);
        commonRightText.setVisibility(View.GONE);
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        getAppCateList();
    }

    @OnClick({R.id.common_back, R.id.send_tv,R.id.show_area_rl,R.id.company_type_rl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                finish();
                break;
            case R.id.company_type_rl://种类
                if (0 != mCateList.size()) {
                    showJobPickciew();
                }
                break;
            case R.id.show_area_rl://展出地区
                
                if (0 != options1Items.size()){
                    if (!FastUtils.isFastDoubleClick()) {
                        //判断软键盘是否打开，为true则关闭，否则不处理
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        boolean isOpen = imm.isActive();
                        if (isOpen) {
                            closrKeyboard();
                        }
                        provinceId = "1";// 省id
                        cityId = "2";//市 id
                        distristId = "3";//区id
                        //城市选择弹出框
                        CityPickerPopWindow2 mPopWindow = new CityPickerPopWindow2(this,options1Items);
                        mPopWindow.showPopupWindow(root_layout);
                        mPopWindow.setCityPickListener(this);
                    }
                }
                break;
            case R.id.send_tv://发布
                if (checkIsEmpty()){
                    sendYellowPageData(companyPhone.getText().toString().trim(),detailEt.getText().toString().trim());
                }
                break;
        }
    }

    //判断是否为空
    private boolean checkIsEmpty(){
        if (TextUtils.isEmpty(companyNameEt.getText().toString().trim())){
            MyToast("请输入企业名称!");
            return false;
        }
        if (TextUtils.isEmpty(companyPhone.getText().toString().trim())){
            MyToast("请输入企业电话!");
            return false;
        }
        if (TextUtils.isEmpty(detailEt.getText().toString().trim())){
            MyToast("请输入详细地址!");
            return false;
        }
        if (TextUtils.isEmpty(companyType)){
            MyToast("请选择企业种类!");
            return false;
        }
        if (TextUtils.isEmpty(showAreaTv.getText().toString().trim())){
            MyToast("请选择展出地区!");
            return false;
        }
        return true;
    }
    
    //发布黄页
    private void sendYellowPageData(String telephone,String detailed_address){
        Map<String,Object> params = new HashMap<>();
        params.put("token", Prefer.getInstance().getToken());
        params.put("app_cate_id",app_cate_id);
        params.put("company_name", companyType);
        params.put("telephone",telephone);
        params.put("province",provinceId);
        params.put("city",cityId);
        params.put("area",distristId);
        params.put("detailed_address",detailed_address);
        params.put("area_id","," + distristId +",");
        params.put("release_days","");
        XUtil.Post(UrlConfig.APP_LOCATION_YELLOW_PAGES_ADD,params,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("TAG:sendYellowPage," ,result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (1 == jsonObject.optInt("code")){
                        Gson gson = new Gson();
                        HomeSendYellowPageS yellowPageS = gson.fromJson(result,HomeSendYellowPageS.class);
                        String orderNo = yellowPageS.getData().getOrder();
                        //目前只请求下支付接口，因为发布黄页是要付费的
                        payForPage(orderNo);
                        //如果发布成功
                   
                    }else if (100 == jsonObject.optInt("code")){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        MyToast(jsonObject.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    //发布支付
    private void payForPage(String order){
       Map<String,Object> params = new HashMap<>();
       params.put("token",Prefer.getInstance().getToken());
       params.put("order",order);
       params.put("pay_type",1);//支付类型：1-支付宝;2-微信;3-余额;4-银联支付;5-积分支付
       XUtil.Post(UrlConfig.SUPPLY_FILE_PAY,params,new MyCallBack<String>(){
           @Override
           public void onSuccess(String result) {
               super.onSuccess(result);
               Intent intent = new Intent();
               setResult(MY_SEND_PAGE,intent);
               finish();
           }

           @Override
           public void onFinished() {
               super.onFinished();
           }

           @Override
           public void onError(Throwable ex, boolean isOnCallback) {
               super.onError(ex, isOnCallback);
           }
       }); 
    }
    
    /**
     * 企业种类
     */
    private void showJobPickciew() {
        if (mCateList.size() == 0) {
            MyToast("暂无可选项目");
            return;
        }
        List<String> list = new ArrayList<>();
        for (int i = 0; i < mCateList.size(); i++) {
            list.add(mCateList.get(i).getName());
        }
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                companyId = mCateList.get(options1).getId();
                companyType = mCateList.get(options1).getName();
                companyTypeTv.setText(mCateList.get(options1).getName());
            }
        })

                .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                .setTitleColor(getResources().getColor(R.color.text))//标题文字颜色)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.red2552))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.red2552))//取消按钮文字颜色.build();
                .setCyclic(false, false, false)
                .build();
        pvOptions.setPicker(list);//一级选择器
        pvOptions.show();
    }
    
    //获取企业中雷
    private void getAppCateList() {
        Map<String, Object> params = new HashMap<>();
        params.put("id", 54);
        XUtil.Post(UrlConfig.APP_CATE_LIST, params, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (1 == jsonObject.optInt("code")) {
                        Gson gson = new Gson();
                        HomeAppFzSchoolBean schoolBean = gson.fromJson(result, HomeAppFzSchoolBean.class);
                        if (null != schoolBean) {
                            if (null != mCateList) {
                                mCateList.clear();
                            }
                            mCateList.addAll(schoolBean.getData());
                            
                        }
                    } else if (100 == jsonObject.optInt("code")) {
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    } else {
                        MyToast(jsonObject.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }    

    private void initJsonData(Context context) {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(context, "region.json");//获取assets目录下的json文件数据

        ArrayList<ProvinceBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            List<ProvinceBean.TwoRegBean> CityList = new ArrayList<>();//该省的城市列表（第二级）
            List<ProvinceBean.TwoRegBean.ThreeRegBean> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getTwo_reg().size(); c++) {//遍历该省份的所有城市
                CityList.add(jsonBean.get(i).getTwo_reg().get(c));//添加城市
                List<ProvinceBean.TwoRegBean.ThreeRegBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (null == jsonBean.get(i).getTwo_reg().get(c).getThree_reg()
                        || jsonBean.get(i).getTwo_reg().get(c).getThree_reg().size() == 0) {
                    City_AreaList.add(new ProvinceBean.TwoRegBean.ThreeRegBean());
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getTwo_reg().get(c).getThree_reg());
                }
                Province_AreaList.addAll(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.addAll(CityList);

            /**
             * 添加地区数据
             */
            options3Items.addAll( Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData(LocationYellowSendActivity.this);
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    public ArrayList<ProvinceBean> parseData(String result) {//Gson 解析
        ArrayList<ProvinceBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                ProvinceBean entity = gson.fromJson(data.optJSONObject(i).toString(), ProvinceBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }




    @Override
    public void pickValue(String value) {
        province = value.split("-")[0];
        city = value.split("-")[1];
        if (value.split("-").length >= 3) {
            district = value.split("-")[2];
            showAreaTv.setText(province + "-" + city + "-" +district);
        }else {
            district = " ";
            showAreaTv.setText(province + "-" + city);
        }

        for (int i = 0; i < options1Items.size(); i++) {
            if (province.equals(options1Items.get(i).getName())) {
                provinceId = options1Items.get(i).getId() + "";
            }
        }

        for (int i = 0; i < options2Items.size(); i++) {
            if ((options2Items.get(i).getName().contains(city))){
                cityId = options2Items.get(i).getId() + "";
            }
        }

        if (null != options3Items && 0 != options3Items.size()) {
            for (int i = 0; i < options3Items.size(); i++) {

                if (!TextUtils.isEmpty(district) && options3Items.get(i).getName().contains(district)) {
                    distristId = options3Items.get(i).getId() + "";
                }
            }
        }else {
            distristId = " ";
        }

        Log.e("TAGPROVINCE_ID", provinceId + ":" + cityId + ":" + distristId);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }
}
